﻿using EquipmentAlarmSystem.Service.Models;
using OfficeOpenXml;
using S7.Net;
using System.Text.Json;

namespace 设备报警系统客户端
{
    public partial class 西门子S7设备添加修改 : Form
    {
        public 西门子S7设备添加修改()
        {
            InitializeComponent();
            //忽略其他线程执行UI的错误
            CheckForIllegalCrossThreadCalls = false;
        }
        private string id = "";

        public 西门子S7设备添加修改(string id)
        {
            InitializeComponent();
            //忽略其他线程执行UI的错误
            CheckForIllegalCrossThreadCalls = false;
            this.id = id;
        }

        /// <summary>
        /// 判断是否未空
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        private string iSNull(object o)
        {
            if (o is null)
            {
                return "-1";
            }
            return o.ToString()!;
        }
        private bool isNullBool(object o)
        {
            if (o is not null)
            {
                return bool.Parse(o.ToString()!);
            }
            return false;
        }

        private void btnPreserve_Click(object sender, EventArgs e)
        {
            Form form = new 验证服务();
            if (form.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            DeviceInformationSiemensS7 configuration = new();
            //添加默认行
            configuration.Id = iSNull(DeviceInformation.Rows[0].Cells[0].Value);
            configuration.Name = iSNull(DeviceInformation.Rows[0].Cells[1].Value);
            configuration.Describe = iSNull(DeviceInformation.Rows[0].Cells[2].Value);

            //DeviceAddress
            configuration.CpuType = (CpuType)Enum.Parse(typeof(CpuType), iSNull(DeviceAddress.Rows[0].Cells[0].Value).ToUpper(), true);
            configuration.Protocol = (EquipmentAlarmSystem.Service.Models.Enum.Protocol)Protocol.S7;
            configuration.Ip = iSNull(DeviceAddress.Rows[0].Cells[1].Value);
            configuration.Port = short.Parse(iSNull(DeviceAddress.Rows[0].Cells[2].Value));
            configuration.Rack = short.Parse(iSNull(DeviceAddress.Rows[0].Cells[3].Value));
            configuration.Slot = short.Parse(iSNull(DeviceAddress.Rows[0].Cells[4].Value));
            configuration.IsMultiple = isNullBool(DeviceAddress.Rows[0].Cells[5].Value);
            configuration.PointInformation = new();

            configuration.EnableAutomaticAlarm = isNullBool(AutomaticAlarmView.Rows[0].Cells[0].Value);
            configuration.AutomaticAlarmAddr = iSNull(AutomaticAlarmView.Rows[0].Cells[1].Value);

            //保存数据信息
            for (int i = 0; i < DataAddress.RowCount - 1; i++)
            {
                PointInformation pointInformation = new();

                string alarmAddress = iSNull(DataAddress.Rows[i].Cells[0].Value);

                if (alarmAddress.Length < 3)
                {
                    continue;
                }
                pointInformation.Address = alarmAddress;
                pointInformation.Content = iSNull(DataAddress.Rows[i].Cells[1].Value);
                pointInformation.IsEnabled = isNullBool(DataAddress.Rows[i].Cells[2].Value);
                configuration.PointInformation.Add(pointInformation);
            }

            configuration.Contacts = new();

            //添加联系人
            for (int i = 0; i < Contacts.RowCount - 1; i++)
            {
                if (iSNull(Contacts.Rows[i].Cells[0].Value) == "未配置")
                {
                    continue;
                }
                Contact contact = new();
                foreach (var item in Basic.Config.Contacts)
                {
                    if (item.Name == iSNull(Contacts.Rows[i].Cells[0].Value))
                    {
                        contact.Name = item.Name;
                        contact.EnableSms = isNullBool(Contacts.Rows[i].Cells[1].Value);
                        contact.EnableDialing = isNullBool(Contacts.Rows[i].Cells[2].Value);
                        configuration.Contacts.Add(contact);
                    }
                }
            }
            _ = Basic.HttpPostAsync("/Equipment/ModifyEquipmentSiemensS7", configuration);

            this.Close();
        }

        private void LoadData()
        {
            var conf = JsonSerializer.Deserialize<DeviceInformationSiemensS7>(Basic.HttpGet($"/Equipment/GetEquipment?id={id}"));

            this.Invoke(new Action(() =>
            {
                if (conf is not null)
                {
                    try
                    {
                        DeviceInformation.Rows[0].Cells[0].Value = conf!.Id;
                        DeviceInformation.Rows[0].Cells[1].Value = conf!.Name;
                        DeviceInformation.Rows[0].Cells[2].Value = conf!.Describe;

                        DeviceAddress.Rows[0].Cells[0].Value = Enum.GetName(conf.CpuType);
                        DeviceAddress.Rows[0].Cells[1].Value = conf.Ip;
                        DeviceAddress.Rows[0].Cells[2].Value = conf.Port;
                        DeviceAddress.Rows[0].Cells[3].Value = conf.Rack;
                        DeviceAddress.Rows[0].Cells[4].Value = conf.Slot;
                        DeviceAddress.Rows[0].Cells[5].Value = conf.IsMultiple;

                        AutomaticAlarmView.Rows[0].Cells[0].Value = conf.EnableAutomaticAlarm;
                        AutomaticAlarmView.Rows[0].Cells[1].Value = conf.AutomaticAlarmAddr;

                        Contacts.Rows.Clear();
                        if (conf.Contacts is not null)
                        {
                            foreach (var item in conf.Contacts)
                            {
                                int index = Contacts.Rows.Add();
                                Contacts.Rows[index].Cells[0].Value = item.Name;
                                Contacts.Rows[index].Cells[1].Value = item.EnableSms;
                                Contacts.Rows[index].Cells[2].Value = item.EnableDialing;
                            }
                        }

                        DataAddress.Rows.Clear();
                        if (conf.PointInformation is not null)
                        {
                            foreach (var item in conf.PointInformation)
                            {
                                int index = DataAddress.Rows.Add();
                                DataAddress.Rows[index].Cells[0].Value = item.Address;
                                DataAddress.Rows[index].Cells[1].Value = item.Content;
                                DataAddress.Rows[index].Cells[2].Value = item.IsEnabled;
                            }
                        }
                    }
                    catch (Exception)
                    {

                    }
                }
            }));
        }

        private void 西门子S7设备添加修改_Load(object sender, EventArgs e)
        {
            //添加默认行
            AutomaticAlarmView.Rows.Add();

            DeviceAddress.Rows.Add();

            DeviceInformation.Rows.Add();
            //CPU TYPE
            Column21.DataSource = Enum.GetNames(typeof(CpuType));

            //添加联系人
            //Contacts.Rows.Add();
            var contacts = Basic.Config.Contacts;

            if (contacts is not null && contacts.Count >= 1)
            {
                List<string> strings = ["未配置"];

                foreach (var item in contacts)
                {
                    strings.Add(item.Name);
                }
                Column4.DataSource = strings;
            }

            if (id.Length >= 4)
            {
                LoadData();
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < DataAddress.RowCount - 1; i++)
            {
                DataAddress.Rows[i].Cells[3].Value = "---";
            }
            try
            {
                string type = iSNull(DeviceAddress.Rows[0].Cells[0].Value);
                CpuType cpuType = (CpuType)Enum.Parse(typeof(CpuType), type.ToUpper(), true);
                string ip = iSNull(DeviceAddress.Rows[0].Cells[1].Value);
                string port = iSNull(DeviceAddress.Rows[0].Cells[2].Value);
                string rack = iSNull(DeviceAddress.Rows[0].Cells[3].Value);
                string slot = iSNull(DeviceAddress.Rows[0].Cells[4].Value);

                Plc plc = new(cpuType, ip, short.Parse(port), short.Parse(rack), short.Parse(slot));

                plc.Open();

                try
                {
                    this.Invoke(new Action(() =>
                    {
                        if (isNullBool(AutomaticAlarmView.Rows[0].Cells[0].Value))
                        {
                            AutomaticAlarmView.Rows[0].Cells[2].Value = (bool)plc.Read(iSNull(AutomaticAlarmView.Rows[0].Cells[1].Value))!;
                        }
                        for (int i = 0; i < DataAddress.RowCount; i++)
                        {
                            string alarmAddress = iSNull(DataAddress.Rows[i].Cells[0].Value);

                            if (alarmAddress.Length < 3)
                            {
                                continue;
                            }
                            DataAddress.Rows[i].Cells[3].Value = (bool)plc.Read(iSNull(DataAddress.Rows[i].Cells[0].Value).ToUpper())!;
                        }
                    }));
                }
                catch (Exception ex)
                {

                    throw new ($"数据读取错误:{ex.Message}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"设备连接失败 {ex.Message}", "设备连接", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            var dialogResult = MessageBox.Show("仅支持 excel\n工作簿：Sheet1\n第一列为：地址栏\n第二列为：报警信息！", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

            if (dialogResult != DialogResult.Yes)
            {
                return;
            }

            OpenFileDialog filedialog = new OpenFileDialog();

            filedialog.CheckFileExists = true;

            filedialog.CheckPathExists = true;

            filedialog.Filter = "所有文件(*.*)|*.*"; ;

            DialogResult ret = filedialog.ShowDialog();

            if (ret == DialogResult.OK)
            {
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

                using (var package = new ExcelPackage(new FileInfo(filedialog.FileName!)))
                {
                    try
                    {
                        //获取工作簿
                        var sheets = package.Workbook.Worksheets["Sheet1"];
                        //有效行
                        int iRowCount = sheets.Dimension.End.Row;
                        //有效列
                        int colCount = sheets.Dimension.End.Column;

                        DataAddress.Rows.Clear();

                        for (int i = 1; i <= iRowCount; i++)
                        {
                            if (sheets.Cells[i, 1].Value != null)
                            {
                                int index = DataAddress.Rows.Add();

                                DataAddress.Rows[index].Cells[0].Value = sheets.Cells[i, 1].Value;

                                if (sheets.Cells[i, 2].Value != null)
                                {
                                    DataAddress.Rows[index].Cells[1].Value = sheets.Cells[i, 2].Value;
                                }
                            }
                        }

                        package.Save();
                    }
                    catch (Exception ex)
                    {
                        package.Save();
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }
    }
}
